package com.company.wechatpush.service;

import com.company.wechatpush.config.PushConfig;
import com.company.wechatpush.config.WeatherConfig;
import com.company.wechatpush.entity.Result;
import com.company.wechatpush.entity.User;
import com.company.wechatpush.entity.UserList;
import com.company.wechatpush.entity.Weather;
import com.company.wechatpush.utils.LunarFestivalUtil;
import com.company.wechatpush.utils.MemoryDayUtil;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxMpTemplateMsgService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @author Real
 * @since 2022-09-03 12:20 AM
 */
@Service
public class PushService {

    @Autowired
    private UserList userList;

    private static WxMpTemplateMsgService wxService = null;

    /**
     * 默认时区代码
     */
    private static final String DEFAULT_CODE = "110100";

    /**
     * 消息推送主要业务代码
     */
    public String push() {
        int suc = 0;
        int err = 0;
        User[] users = userList.getUsers();
        for (User user : users) {
            // 构建模板消息
            WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                    .templateId(PushConfig.getTemplateId())
                    .build();
            String districtId = user.getDistrictId();
            districtId = Optional.ofNullable(districtId).orElse(DEFAULT_CODE);
            user.setDistrictId(districtId);
            // 计算天数
            long loveDays = MemoryDayUtil.calculateLoveDay(user.getLoveDate());
            long birthdays = 0;
            if (user.isUseLunar()) {
                // 如果使用农历生日
                birthdays = MemoryDayUtil.calculationBirthdayByLunar(user.getBirthday());
            } else {
                birthdays = MemoryDayUtil.calculationBirthday(user.getBirthday());
            }
            templateMessage.addData(new WxMpTemplateData("loveDays", loveDays + "", "#FF1493"));
            templateMessage.addData(new WxMpTemplateData("birthdays", birthdays + "", "#FFA500"));

            // 获取天气数据
            Result<Weather> weatherResult = WeatherService.getWeather(user);
            if (weatherResult.getCode() != 200) {
                templateMessage.addData(new WxMpTemplateData("weather", "***", "#00FFFF"));
            } else {
                Weather weather = weatherResult.getData();
                // 拿到农历日期
                LunarFestivalUtil festival = new LunarFestivalUtil();
                festival.initLunarCalendarInfo(weather.getDate());

                templateMessage.addData(new WxMpTemplateData("date", weather.getDate() + "  " + weather.getWeek(), "#00BFFF"));
                templateMessage.addData(new WxMpTemplateData("lunar", "农历" + festival.getLunarYear() + "年 " + festival.getLunarMonth() + "月" + festival.getLunarDay(), "#00BFFF"));
                templateMessage.addData(new WxMpTemplateData("festival", festival.getLunarTerm() + " " + festival.getSolarFestival() + " " + festival.getLunarFestival(), "#00BFFF"));
                templateMessage.addData(new WxMpTemplateData("weather", weather.getTextNow(), "#00FFFF"));
                templateMessage.addData(new WxMpTemplateData("low", weather.getLow() + "", "#173177"));
                templateMessage.addData(new WxMpTemplateData("temp", weather.getTemp() + "", "#EE212D"));
                templateMessage.addData(new WxMpTemplateData("wc_day", weather.getWcDay() + "", "#EE212D"));
                templateMessage.addData(new WxMpTemplateData("wd_day", weather.getWdDay() + "", "#EE212D"));
                templateMessage.addData(new WxMpTemplateData("high", weather.getHigh() + "", "#FF6347"));
                templateMessage.addData(new WxMpTemplateData("city", weather.getCityName() + "", "#173177"));

                // 填充天气诗句
                String textNow = weather.getTextNow();
                Integer weatherType = WeatherConfig.getWeatherType(textNow);
                Result<String> weatherPoem = WeatherService.getWeatherPoem(weatherType);
                if (weatherPoem.getCode() == 200) {
                    templateMessage.addData(new WxMpTemplateData("poem", weatherPoem.getData(), "#FF00DF"));
                }
            }

            // 天行数据接口
            Result<String> rainbowResult = RainbowService.getRainbow();
            if (rainbowResult.getCode() == 200) {
                templateMessage.addData(new WxMpTemplateData("rainbow", rainbowResult.getData(), "#FF69B4"));
            }
            // 备注
            String remark = "❤";
            if (loveDays % 365 == 0) {
                remark = "\n今天是恋爱" + (loveDays / 365) + "周年纪念日！";
            }
            if (birthdays == 0) {
                remark = "\n今天是生日，生日快乐呀！";
            }
            if (loveDays % 365 == 0 && birthdays == 0) {
                remark = "\n今天是生日，也是恋爱" + (loveDays / 365) + "周年纪念日！";
            }
            templateMessage.addData(new WxMpTemplateData("remark", remark, "#FF1493"));


            System.out.println(templateMessage.toJson());

            // 拿到service
            WxMpTemplateMsgService service = getService();
            templateMessage.setToUser(user.getUserId());
            try {
                service.sendTemplateMsg(templateMessage);
                suc += 1;
            } catch (WxErrorException e) {
                err += 1;
                return "推送结果：" + suc + "成功，" + err + "失败";
            }
        }
        return "成功推送给" + suc + "个用户！";
    }

    /**
     * 获取 WxMpTemplateMsgService
     *
     * @return WxMpTemplateMsgService
     */
    private static WxMpTemplateMsgService getService() {
        if (wxService != null) {
            return wxService;
        }
        WxMpInMemoryConfigStorage wxStorage = new WxMpInMemoryConfigStorage();
        wxStorage.setAppId(PushConfig.getAppId());
        wxStorage.setSecret(PushConfig.getSecret());
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxStorage);
        wxService = wxMpService.getTemplateMsgService();
        return wxService;
    }
}
